import { Context } from 'koa'
import { getListSer, addSer, putSer, getDetailSer, delSer, addFiles , addSerArr } from '@/business/service'
import { userType } from '@/types'
import { IQueryType, IQuerySerType, I, ISer } from '@/types/equipment/uploadIni'
import errors from '@/app/err.type'
import { formatHumpLineTransfer } from '@/business/utils'
import { excelJsExport } from '@/business/utils/excel'
import { generateFileId, parseFiles, checkFiles, mockStandrdData } from '@/business/utils/format';
import { excelBaseStyle } from '@/business/public/excelMap'
import EquipmentEquipmentupload from '@/mysql/model/equipment/uploadIni.model'
import JiaoyanjieguoTable from '@/mysql/model/equipment/jiaoyantable.model'
import { Op } from 'sequelize'
import { updatePassword, getAllUserInfoSer } from '@/business/service/user.service';
import fs from 'fs';

const { uploadParamsErr, getListErr, sqlErr, delErr, exportExcelErr } = errors

const iniSqlData  = [
    {
      table_id: 3,
      dept_id: null,
      file_type: "许继ini",
      key: "external_temp_coeff_TG56",
      work_type: "年检",
      min: 1,
      max: 4,
      equal: 8,
      need_check: 1,
      user_id: "",
      create_by: "admin",
      update_by: "",
      created_at: "2024-03-05 19:50:54",
      filed1: "",
      updated_at: "2024-03-05 19:50:54",
      filed2: "",
    },
    {
      table_id: 8,
      dept_id: 1,
      file_type: "许继ini",
      key: "external_temp_coeff_TG40",
      work_type: "年检",
      min: null,
      max: null,
      equal: 4,
      need_check: 1,
      user_id: "",
      create_by: "admin",
      update_by: "",
      created_at: "2024-03-10 20:52:03",
      filed1: "",
      updated_at: "2024-03-10 20:52:03",
      filed2: "",
    },
    {
        table_id: 8,
        dept_id: 1,
        file_type: "许继ini",
        key: "external_temp_coeff_TG24",
        work_type: "年检",
        min: null,
        max: null,
        equal: 12,
        need_check: 1,
        user_id: "",
        create_by: "admin",
        update_by: "",
        created_at: "2024-03-10 20:52:03",
        filed1: "",
        updated_at: "2024-03-10 20:52:03",
        filed2: "",
      },
  ];
  const bkpSqlData  = [
    {
      table_id: 3,
      dept_id: null,
      file_type: "bkp",
      key: "0xB9",
      work_type: "年检",
      min: 1,
      max: 4,
      equal: 7,
      need_check: 1,
      user_id: "",
      create_by: "admin",
      update_by: "",
      created_at: "2024-03-05 19:50:54",
      filed1: "",
      updated_at: "2024-03-05 19:50:54",
      filed2: "",
    },
    {
      table_id: 8,
      dept_id: 1,
      file_type: "bkp",
      key: "0xBA",
      work_type: "年检",
      min: null,
      max: null,
      equal: -30.000000,
      need_check: 1,
      user_id: "",
      create_by: "admin",
      update_by: "",
      created_at: "2024-03-10 20:52:03",
      filed1: "",
      updated_at: "2024-03-10 20:52:03",
      filed2: "",
    },
    {
        table_id: 8,
        dept_id: 1,
        file_type: "bkp",
        key: "0xC0",
        work_type: "年检",
        min: null,
        max: null,
        equal: 6.304000,
        need_check: 1,
        user_id: "",
        create_by: "admin",
        update_by: "",
        created_at: "2024-03-10 20:52:03",
        filed1: "",
        updated_at: "2024-03-10 20:52:03",
        filed2: "",
      },
  ];
// 获取列表
export const getListMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { pageNum, pageSize, ...params } = ctx.query as unknown as IQueryType
    const newParams = { pageNum, pageSize } as IQuerySerType

    const res = await getListSer<IQuerySerType>(EquipmentEquipmentupload, newParams)

    ctx.state.formatData = res
    await next()
  } catch (error) {
    console.error('查询列表失败', error)
    return ctx.app.emit('error', getListErr, ctx)
  }
}

// 新增
export const getAddMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    if (ctx.request.body) {

      const { userName } = ctx.state.user as userType
      const addContent = ctx.request?.body as I
      const addContent2 = { ...addContent, createBy: userName }
      const newAddContent = formatHumpLineTransfer(addContent2, 'line') as ISer
  
      await addSer<ISer>(EquipmentEquipmentupload, newAddContent)
    }
    await next()
  } catch (error) {
    console.error('新增失败', error)
    return ctx.app.emit('error', uploadParamsErr, ctx)
  }
}

// 删除
export const delMid = async (ctx: Context, next: () => Promise<void>) => {
  try {

    await delSer(EquipmentEquipmentupload, { table_id: ctx.state.ids })
  } catch (error) {
    console.error('删除失败', error)
    return ctx.app.emit('error', delErr, ctx)
  }

  await next()
}

// 获取详细数据
export const getDetailMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const res = await getDetailSer<ISer>(EquipmentEquipmentupload, { table_id: ctx.state.ids })

    ctx.state.formatData = res
  } catch (error) {
    console.error('详细数据查询错误', error)
    return ctx.app.emit('error', sqlErr, ctx)
  }

  await next()
}

// 修改
export const putMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    if (ctx.request.body) {

      const { userName } = ctx.state.user as userType;
      const res = ctx.request?.body as I;
      const lineData = formatHumpLineTransfer(res, 'line') as ISer;
      const { ...data } = lineData;
  
      await putSer<ISer>(EquipmentEquipmentupload, { table_id: ctx.state.ids }, { ...data, update_by: userName });
    }

    await next();
  } catch (error) {
    console.error('修改失败', error);
    return ctx.app.emit('error', uploadParamsErr, ctx)
  }
}

// 导出
export const exportMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const list = ctx.state.formatData
    const { dicts } = ctx.state

    // 表格数据
    const buffer = await excelJsExport({
      sheetName: '代码生成表',
      style: excelBaseStyle,
      headerColumns: [],
      tableData: list,
      dicts
    })
    ctx.state.buffer = buffer
    await next()
  } catch (error) {
    console.error('导出失败', error)
    return ctx.app.emit('error', exportExcelErr, ctx)
  }
}




// 上传ini文件
export const uploadIniMid = async (ctx: Context, next: () => Promise<void>) => {
  // iniFiles是前端传的参数
  const fileArr = []
  const { files } = (ctx.request as any);
  if (!Array.isArray(files.iniFiles)) {
    fileArr.push(files.iniFiles)
  } else {
    fileArr.push(...files.iniFiles)
  }
  // 找出用户id 关联的 部门id
  const { userId } = ctx.state.user as userType;
  const { password, ...userRes } = await getAllUserInfoSer({ userId });
  const finRes = { ...userRes };
  const {dept_id} = finRes
  const addItems = [
    // {
    //   filepath: 'file.filepath',
    //   original_filename: 'file.originalFilename',
    //   new_filename: 'fileId',
    //   jiaoyanjieguo: JSON.stringify(finRes),  
    //   dept_id  
    // },
    // {
    //   filepath: 'file.filepath1',
    //   original_filename: 'file.originalFilename1',
    //   new_filename: 'fileId1',
    //   jiaoyanjieguo: JSON.stringify([]),  
    //   dept_id     
    // }
  ]
  await Promise.all(fileArr.map((file: any) => new Promise<void>((resolve,reject) =>{
      fs.readFile(file.filepath, 'utf-8', (err, data) => {
        if (err) {
          console.log("读取文件失败-----")
          reject()
        }
        // 获取上传文件名 todo
        const fileName = 'originalname';
        // 使用正则表达式匹配文件后缀
        const isINI = /\.ini$/.test(fileName);
        const initSqlRules = isINI ? iniSqlData : bkpSqlData;
        const checkRules = initSqlRules.map(item => ({ key: item.key, equal: item.equal }));
        /// 解析文件内容
        const resultData = parseFiles(data, fileName);
        // 校验
        const checkedData = checkFiles(checkRules, resultData);
        // filepath,new_filename:newFilename,original_filename:originalFilename
        addItems.push({
          filepath: file.filepath,
          original_filename: file.originalFilename,
          new_filename: 'fileId',
          jiaoyanjieguo: JSON.stringify(checkedData),
          dept_id
        })
        resolve()
      }); 
    }))).then(async () => {

    // 入库
    const res = await addSerArr(JiaoyanjieguoTable, addItems)
    
  })
  await next();
};


 